//
//  TECommon.m
//  TintExample
//
//  Created by Kevin Wu on 8/31/12.
//  Copyright (c) 2012 Telligenty. All rights reserved.
//

#import "TECommon.h"

id TECreateList()
{
    return [[NSMutableArray alloc] init];
}


id TEAddGroup(id list, NSString *name)
{
    if ( list && name ) {
        
        NSDictionary *group = TEGroupByName(list, name);
        
        if ( group == nil ) {
            NSMutableArray *examples = [[NSMutableArray alloc] init];
            group = [[NSDictionary alloc] initWithObjectsAndKeys:
                     name, @"group_name", 
                     examples, @"group_examples", nil];
            [examples release];
            [list addObject:group];
            [group release];
        }
        
        return TEGroupByName(list, name);
    }
    return nil;
}

id TEGroupByName(id list, NSString *name)
{
    for ( NSDictionary *g in list ) {
        NSString *n = TENameOfGroup(g);
        if ( [n isEqualToString:name] ) {
            return g;
        }
    }
    return nil;
}

NSString *TENameOfGroup(id group)
{
    return [group objectForKey:@"group_name"];
}

NSArray *TEExamplesOfGroup(id group)
{
    return [group objectForKey:@"group_examples"];
}



id TEAddExample(id examples, NSString *name, Class controller)
{
    if ( examples && name ) {
        NSDictionary *example = TEExampleByName(examples, name);
        
        if ( example == nil ) {
            example = [[NSDictionary alloc] initWithObjectsAndKeys:
                       name, @"example_name", 
                       NSStringFromClass(controller), @"example_controller", nil];
            [examples addObject:example];
            [example release];
        }
        
        return TEExampleByName(examples, name);
    }
    return nil;
}

id TEExampleByName(id examples, NSString *name)
{
    for ( NSDictionary *e in examples ) {
        NSString *n = TENameOfExample(e);
        if ( [n isEqualToString:name] ) {
            return e;
        }
    }
    return nil;
}

NSString *TENameOfExample(id example)
{
    return [example objectForKey:@"example_name"];
}

Class TEControllerOfExample(id example)
{
    return NSClassFromString([example objectForKey:@"example_controller"]);
}
